package com.talent.web.config.security.phone;

import com.talent.web.config.security.TalentUserDetailService;
import com.talent.web.config.security.TalentUserDetails;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @ClassName：SmsCodeAuthenticationProvider
 * @Author: hszhou
 * @Date: 2025/2/28 14:08
 * @Description: 实现认证处理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {


    @Autowired
    private final TalentUserDetailService userDetailService;

    @Autowired
    private final SmsCodeService smsCodeService;



    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String mobile = (String) authentication.getPrincipal();
        String code = (String) authentication.getCredentials();
        // 验证码校验
        if (!smsCodeService.validateCode(mobile, code)) {
            System.out.println("验证码错误或已过期");
            throw new BadCredentialsException("验证码错误或已过期");
        }
        TalentUserDetails userDetails = userDetailService.loadUserByMobile(mobile);
        if(userDetails==null){
            throw new BadCredentialsException("手机未注册");
        }

        // 4. 返回已认证的令牌（清除验证码）
//        return new SmsCodeAuthenticationToken(, phone);
        return new SmsCodeAuthenticationToken(userDetails, null, userDetails.getAuthorities());


    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
